package com.resume.aipeople.controller;

import com.resume.aipeople.service.ai.LLMService;
import com.resume.aipeople.service.ai.VoiceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/test")
@RequiredArgsConstructor
@Slf4j
public class TestController {
    
    private final LLMService llmService;
    private final VoiceService voiceService;
    
    @Value("${baidu.voice.api.key:your-baidu-api-key}")
    private String baiduApiKey;
    
    @Value("${baidu.voice.secret.key:your-baidu-secret-key}")
    private String baiduSecretKey;
    
    @Value("${baidu.voice.app.id:your-app-id}")
    private String baiduAppId;
    
    @GetMapping("/llm")
    public Mono<ResponseEntity<Map<String, Object>>> testLLM() {
        log.info("测试LLM接口");
        
        return llmService.generateResponse("你好，请简单介绍一下自己", "Harry Potter", "test-session")
                .map(response -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("message", "LLM测试成功");
                    result.put("response", response);
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "LLM测试失败",
                    "error", "LLM服务不可用"
                )));
    }
    
    @PostMapping("/tts")
    public Mono<ResponseEntity<Map<String, Object>>> testTTS(@RequestParam String text, 
                                                           @RequestParam(defaultValue = "Harry Potter") String character) {
        log.info("测试TTS接口: text={}, character={}", text, character);
        
        return voiceService.textToSpeech(text, character)
                .map(audioUrl -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("message", "TTS测试成功");
                    result.put("audioUrl", audioUrl);
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "TTS测试失败",
                    "error", "TTS服务不可用"
                )));
    }
    
    @PostMapping("/asr")
    public Mono<ResponseEntity<Map<String, Object>>> testASR(@RequestParam("file") MultipartFile file) {
        log.info("测试ASR接口: filename={}, size={}KB", file.getOriginalFilename(), file.getSize() / 1024);
        
        return voiceService.speechToText(file)
                .map(text -> {
                    Map<String, Object> result = new HashMap<>();
                    result.put("success", true);
                    result.put("message", "ASR测试成功");
                    result.put("text", text);
                    result.put("filename", file.getOriginalFilename());
                    result.put("fileSize", file.getSize());
                    result.put("sdk", "BaiduAipSpeech"); // 标识使用的是百度SDK
                    return ResponseEntity.ok(result);
                })
                .onErrorReturn(ResponseEntity.ok(Map.of(
                    "success", false,
                    "message", "ASR测试失败",
                    "error", "ASR服务不可用"
                )));
    }
    
    @GetMapping("/health")
    public ResponseEntity<Map<String, Object>> healthCheck() {
        Map<String, Object> result = new HashMap<>();
        result.put("status", "UP");
        result.put("message", "AI People服务运行正常");
        result.put("timestamp", System.currentTimeMillis());
        return ResponseEntity.ok(result);
    }
    
    @GetMapping("/baidu-tts-config")
    public ResponseEntity<Map<String, Object>> checkBaiduTTSConfig() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查API配置状态
            boolean apiConfigured = !baiduApiKey.equals("your-baidu-api-key") && 
                                  !baiduSecretKey.equals("your-baidu-secret-key") && 
                                  !baiduAppId.equals("your-app-id");
            
            result.put("apiConfigured", apiConfigured);
            result.put("apiKey", baiduApiKey.substring(0, Math.min(8, baiduApiKey.length())) + "...");
            result.put("appId", baiduAppId);
            
            if (apiConfigured) {
                result.put("status", "CONFIGURED");
                result.put("message", "百度TTS API已配置，如果仍有权限错误，请检查：\n" +
                                     "1. 是否已在百度智能云控制台开通语音合成服务\n" +
                                     "2. 是否已领取「语音合成-基础音库」免费额度\n" +
                                     "3. API Key是否有TTS权限");
                result.put("nextSteps", Map.of(
                    "step1", "登录百度智能云控制台：https://console.bce.baidu.com/",
                    "step2", "进入语音技术服务",
                    "step3", "确认已开通语音合成服务",
                    "step4", "领取免费额度（关键步骤）",
                    "step5", "检查API权限设置"
                ));
            } else {
                result.put("status", "NOT_CONFIGURED");
                result.put("message", "百度TTS API未配置，当前使用模拟音频");
                result.put("configHelp", "请在application.yml中配置正确的百度API信息");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("检查百度TTS配置时出错", e);
            result.put("status", "ERROR");
            result.put("message", "检查配置时出错：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
    
    @GetMapping("/baidu-asr-config")
    public ResponseEntity<Map<String, Object>> checkBaiduASRConfig() {
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 检查API配置状态
            boolean apiConfigured = !baiduApiKey.equals("your-baidu-api-key") && 
                                  !baiduSecretKey.equals("your-baidu-secret-key") && 
                                  !baiduAppId.equals("your-app-id");
            
            result.put("apiConfigured", apiConfigured);
            result.put("apiKey", baiduApiKey.substring(0, Math.min(8, baiduApiKey.length())) + "...");
            result.put("appId", baiduAppId);
            
            if (apiConfigured) {
                result.put("status", "CONFIGURED");
                result.put("message", "百度ASR API已配置");
                result.put("supportedFormats", Map.of(
                    "推荐格式", "PCM (原始音频数据，识别效果最好)",
                    "支持格式", "WAV, AMR, PCM",
                    "采样率", "16000Hz (推荐) 或 8000Hz",
                    "音频长度", "1-60秒"
                ));
                result.put("optimizationTips", Map.of(
                    "tip1", "使用16000Hz采样率获得最佳识别效果",
                    "tip2", "确保音频清晰，避免背景噪音",
                    "tip3", "音频时长建议1-10秒，过长或过短会影响识别",
                    "tip4", "PCM格式识别效果最佳，WAV次之",
                    "tip5", "避免使用压缩格式（如MP3）"
                ));
            } else {
                result.put("status", "NOT_CONFIGURED");
                result.put("message", "百度ASR API未配置，当前使用模拟识别");
                result.put("configHelp", "请在application.yml中配置正确的百度API信息");
            }
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("检查百度ASR配置时出错", e);
            result.put("status", "ERROR");
            result.put("message", "检查配置时出错：" + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
    
    @GetMapping("/audio-files")
    public ResponseEntity<Map<String, Object>> getAudioFiles() {
        try {
            // 调用AudioController的静态方法获取音频列表
            // 由于静态方法无法直接调用，我们通过HTTP请求获取
            Map<String, Object> result = new HashMap<>();
            result.put("message", "音频文件列表");
            result.put("endpoints", Map.of(
                "asrList", "/api/audio/asr/list",
                "uploadInfo", "/api/audio/asr/upload",
                "description", "访问 /api/audio/asr/list 查看所有保存的语音输入音频文件"
            ));
            result.put("usage", Map.of(
                "step1", "进行语音输入",
                "step2", "音频会自动保存",
                "step3", "访问 /api/audio/asr/list 查看保存的音频",
                "step4", "点击音频URL可以播放或下载"
            ));
            
            return ResponseEntity.ok(result);
            
        } catch (Exception e) {
            log.error("获取音频文件列表时出错", e);
            Map<String, Object> result = new HashMap<>();
            result.put("error", "获取音频文件列表失败: " + e.getMessage());
            return ResponseEntity.ok(result);
        }
    }
}
